<?php
/**
 * neighbor element class
 *
 * @final
 * @author raphael seebacher <raphasee@ee.ethz.ch>
 * @version 0.01
 */
final class neighbor extends message_element_controller {
    protected static $connection_types = Array(
      'bluetooth',
      'wifi',
    );

    public function get_tag() {
        return 'neighbor';
    }

    protected function update_connection($connection_type) {
        if (array_key_exists('mac', $this->content[$connection_type])) {
            $mac = $this->content[$connection_type]['mac'];

            $connection = new user_connection();
            try {
                $connection->set('user_id', $this->user->get_id());
                $connection->set('type', $connection_type);
                $connection->set('mac', $mac);
                $connection->save();
            }
            catch (model_exception $e) {
                throw new warning(
                  "Updating '$connection_type' MAC address failed."
                );
            }
        }
    }

    protected function get_connection_type_response($connection_type) {
        $mac = Array();
        $radius = config::get('neighbor', 'nearby_radius');

        foreach ($this->user->get_neighbors($radius) as $neighbor) {
            $mac[] = $neighbor->get_mac($connection_type);
        }

        if (count($mac)) {
            $result = Array(
              'status' => 'ok',
              'mac' => $mac,
            );
        }
        else {
            $result = Array(
              'status' => 'error',
              'msg' => 'No neighbors found.'
            );
        }

        return $result;
    }

    protected function process_element() {
        $result = Array();

        $uc = user_controller::get_instance();
        $this->user = $uc->get_user();

        foreach (self::$connection_types as $connection_type) {
            if (array_key_exists($connection_type, $this->content)) {
                $this->update_connection($connection_type);
                $result[$connection_type]
                    = $this->get_connection_type_response($connection_type);
            }
        }

        if (empty($result)) {
            throw new error('No connections given.');
        }

        return $result;
    }
}
?>